<template>
  <div class="edit-page-wrap">
    <Head title="活动信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="edit-form-wrap"
        >
          <el-form-item label="活动名称" prop="name">
            <el-input
              v-model.trim="ruleForm.name"
              placeholder="请输入活动名称"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="活动日期" prop="dates">
            <div class="edit-date-wrap">
              <el-date-picker
                v-model="ruleForm.dates"
                popper-class="qc-date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                valueFormat="YYYY-MM-DD"
                format="YYYY-MM-DD"
                :disabled-date="disabledDate"
              />
            </div>
          </el-form-item>
          <el-form-item label="活动说明" prop="introduce">
            <el-input
              v-model.trim="ruleForm.introduce"
              placeholder="请输入活动说明"
              maxlength="200"
              type="textarea"
              :rows="3"
              show-word-limit
              clearable
            />
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <Head title="活动配置">
      <template #content>
        <el-form
          ref="ruleFormRef1"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="edit-form-wrap"
        >
          <el-form-item label="消费维度" prop="qualifiedType">
            <el-radio-group
              v-model="ruleForm.qualifiedType"
              v-for="(item, index) in ACTIVITY_TYPE"
              :key="index"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.qualifiedType === 2"
            label="奖励标准"
            prop="kwh"
          >
            <el-input
              v-model.trim="ruleForm.kwh"
              placeholder="请输入电度数"
              maxlength="30"
              clearable
            >
              <template #prepend>满</template>
              <template #append>度</template>
            </el-input>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.qualifiedType === 3"
            label="奖励标准"
            prop="money"
          >
            <el-input
              v-model.trim="ruleForm.money"
              placeholder="请输入金额"
              maxlength="30"
              clearable
            >
              <template #prepend>满</template>
              <template #append>元</template>
            </el-input>
          </el-form-item>
        </el-form>
        <ComCoupon
          ref="comCouponRef"
          :activityId="id"
          :labelWidth="80"
        ></ComCoupon>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import Head from '@/components/head/index.vue';
import ComCoupon from '../comCoupon.vue';
import { FormInstance, FormRules } from 'element-plus';
import {
  saveUserActivity,
  updateUserActivity,
  getUserActivityById,
} from '@/service/apis/market';
import { ACTIVITY_TYPE } from '@/utils/dictionaries';
import { IS_DECIMAL_2, IS_DECIMAL_4 } from '@/utils/verify';

const router = useRouter();
const route = useRoute();
const {
  query: { id },
} = route;

const ruleFormRef = ref<FormInstance>();
const ruleFormRef1 = ref<FormInstance>();
const comCouponRef = ref();

const ruleForm = reactive({
  name: '', // 优惠券名称

  dates: [] as any, // 活动日期
  // startTime: '', // 活动开始时间
  // endTime: '', // 活动结束时间

  introduce: '', //活动说明

  qualifiedType: 2, //消费维度
  kwh: '', // 奖励标准-电度数
  money: '', // 奖励标准-金额
});

const disabledDate = (time: any) => {
  return time.getTime() < new Date(new Date().toLocaleDateString()).getTime();
};
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
  dates: [
    { required: true, message: '请选择活动日期', trigger: ['blur', 'change'] },
  ],
  introduce: [{ required: true, message: '请输入活动说明', trigger: 'blur' }],
  qualifiedType: [
    { required: true, message: '请选择消费维度', trigger: ['blur', 'change'] },
  ],
  kwh: [
    { required: true, message: '请输入电度数', trigger: 'blur' },
    {
      pattern: IS_DECIMAL_4,
      message: '请输入正确的电度数，保留4位小数',
      trigger: 'blur',
    },
  ],
  money: [
    { required: true, message: '请输入金额', trigger: 'blur' },
    {
      pattern: IS_DECIMAL_2,
      message: '请输入正确的金额，保留2位小数',
      trigger: 'blur',
    },
  ],
});

if (id) {
  getUserActivityById(id).then((res: any) => {
    if (res) {
      ruleForm.name = res.name;
      ruleForm.introduce = res.introduce;
      ruleForm.dates = [res.startTime, res.endTime];
      ruleForm.qualifiedType = res.qualifiedType;

      comCouponRef.value?.setData(res.detailMap[0]);

      if (res.detailMap && res.detailMap[0].length > 0) {
        if (res.qualifiedType === 2) {
          ruleForm.kwh = res.detailMap[0][0].qualifiedAmount;
        } else {
          ruleForm.money = res.detailMap[0][0].qualifiedAmount;
        }
      }
    }
  });
}

const back = () => {
  router.go(-1);
};

const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (!ruleFormRef.value || !ruleFormRef1.value) return;
  let flag = true;
  let objError = {} as any;
  let comData = [] as any;
  try {
    comData = await Promise.all([
      ruleFormRef.value.validate((e: any, fields: any) => {
        flag = flag ? e : false;
        if (!e) {
          objError = { ...objError, ...fields };
        }
      }),
      ruleFormRef1.value.validate((e: any, fields: any) => {
        flag = flag ? e : false;
        if (!e) {
          objError = { ...objError, ...fields };
        }
      }),
      comCouponRef.value?.getData(),
    ]);
  } catch (e) {}
  if (!flag || !comData[2]) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef.value.scrollToField(key);
        ruleFormRef1.value.scrollToField(key);
        break;
      }
    }
    return;
  }

  const arr = [] as any;
  comData[2].forEach((item: any) => {
    item.qualifiedAmount =
      ruleForm.qualifiedType === 2 ? ruleForm.kwh : ruleForm.money;
    arr.push(item);
  });

  const form: any = {
    type: 3,
    name: ruleForm.name,
    startTime: ruleForm.dates[0],
    endTime: ruleForm.dates[1],
    introduce: ruleForm.introduce,
    qualifiedType: ruleForm.qualifiedType,
    detailMap: { 0: arr },
    participatingCount: 1,
    stationType: 0,
    targetType: 0,
  };

  console.log('form---', form, comData);
  if (id) {
    form.id = id;
    updateUserActivity(form).then((res: any) => {
      emit('clear-cache');
      back();
    });
  } else {
    saveUserActivity(form).then((res: any) => {
      emit('clear-cache');
      back();
    });
  }
};
</script>